<template>
  <div class="page-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-form inline :model="queryForm" @submit.prevent>
          <el-form-item label="品牌名称">
            <el-input
              v-model.trim="queryForm.brandName"
              clearable
              placeholder="请输入品牌名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>
    <!--    <div class="toolbar">-->
    <!--      <el-button :icon="Plus" type="primary" @click="handleEdit($event)">-->
    <!--        添加-->
    <!--      </el-button>-->
    <!--      <el-button :icon="Delete" type="danger" @click="handleDelete($event)">-->
    <!--        批量删除-->
    <!--      </el-button>-->
    <!--    </div>-->
    <div class="opoerate-container toolbar">
      <el-button
        v-permissions="{ role: ['ROOT'], permission: ['sys:assetinfo:add'] }"
        :icon="Plus"
        type="primary"
        @click="handleAddEdit($event)"
      >
        添加
      </el-button>
    </div>
    <el-table
      ref="multipleTableRef"
      v-loading="listLoading"
      border
      :data="list"
      :row-class-name="rowClass"
      height="60vh"
      @cell-dblclick="dblclick"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="50" fixed /> -->
      <el-table-column
        type="index"
        width="80"
        header-align="center"
        align="center"
        label="序号"
        fixed
      />
      <el-table-column
        label="品牌名称"
        prop="brandName"
        show-overflow-tooltip
        header-align="center"
        align="center"
      />
      <el-table-column label="Logo">
        <template #default="scope">
          <el-image
            v-if="scope.row.brandLogo"
            style="width: 100px; height: 100px"
            :src="scope.row.brandLogo"
            :fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="145"
        header-align="center"
        fixed="right"
      >
        <template #default="scope">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑"
            placement="top"
          >
            <el-button
              v-permissions="{
                role: ['ROOT'],
                permission: ['sys:assetinfo:edit'],
              }"
              type="warning"
              :icon="Edit"
              @click="handleAddEdit(scope.row)"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <el-button
              v-permissions="{
                role: ['ROOT'],
                permission: ['sys:assetinfo:delete'],
              }"
              type="danger"
              :icon="Delete"
              @click="handleDelete(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <!-- <edit ref="editRef" @fetch-data="fetchData" /> -->
    <AddAndEdit
      ref="addeditRef"
      :dept-list-data="deptListData"
      @fetch-data="fetchData"
    />
  </div>
</template>

<script>
  import { getList, getBrandDetail, deleteBrand } from '@/api/brand'

  import { fetchDeptList } from '@/api/departmentManagement'
  import {
    Delete,
    Plus,
    Search,
    FolderDelete,
    Edit,
    Message,
    Document,
    FolderChecked,
  } from '@element-plus/icons-vue'
  import { useAclStore } from '@/store/modules/acl'
  export default defineComponent({
    name: 'AssetManagementList',
    components: {
      // Edit: defineAsyncComponent(() => import('./components/edit')),
      AddAndEdit: defineAsyncComponent(() => import('./components/addedit')),
    },
    setup() {
      const router = useRouter()
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const aclStore = useAclStore()
      const { role, permission } = storeToRefs(aclStore)
      const state = reactive({
        editRef: null,
        multipleTableRef: null,
        addeditRef: null,
        list: [],
        DictList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          brandName: '',
          pageNum: 1,
          pageSize: 10,
        },
        statusList: [
          {
            label: '闲置中',
            value: 0,
          },
          {
            label: '使用中',
            value: 1,
          },
          {
            label: '报废',
            value: 2,
          },
        ],
        deptListData: [],
        selectRow: [], // 选中的行
        selectRows: [], // 选中的数据
      })

      watch(
        () => state.selectRows,
        (val) => {
          state.selectRow = []
          if (val.length > 0) {
            state.selectRows.forEach((item) => {
              state.selectRow.push(state.list.indexOf(item))
            })
          }
        },
        {
          deep: true,
        }
      )
      //勾选数据行的 Checkbox 时触发的事件
      const rowClass = ({ rowIndex }) => {
        if (state.selectRow.includes(rowIndex)) {
          return 'slecleRowColor'
        }
      }
      //点击行
      const toggleSelection = (rows) => {
        if (rows) {
          state.multipleTableRef &&
            state.multipleTableRef.toggleRowSelection(rows, undefined)
        } else {
          state.multipleTableRef.clearSelection()
        }
      }

      // 双击跳转详情
      const dblclick = (rows) => {
        handleAddEdit(rows, 'detail')
      }

      // 选中的信息
      const handleSelectionChange = (val) => {
        state.selectRows = val
      }

      const handleAssign = async (row, currentStatus) => {
        try {
          const { data, code } = await getBrandDetail({ deptId: row.id })
          if (code === '1') {
            data.deptId = data.treePath
            state.editRef.showEdit(data, currentStatus)
          } else {
            $baseMessage(msg, 'error', 'vab-hey-message-error')
          }
        } catch (e) {
          console.error(e)
        }
      }

      const handleAddEdit = async (row, type) => {
        if (row.id) {
          try {
            const { data: data } = await getBrandDetail({ id: row.id })
            state.addeditRef.showEdit(data, type)
          } catch (e) {
            console.error(e)
          }
        } else {
          state.addeditRef.showEdit()
        }
      }

      const handleDelete = (row) => {
        // debugger
        if (row.id) {
          try {
            $baseConfirm('你确定要删除当前项吗', '提示', async () => {
              const { msg, code } = await deleteBrand({ id: row.id })
              if (code === '1') {
                $baseMessage(msg, 'success', 'vab-hey-message-success')
                await fetchData()
              } else {
                $baseMessage(msg, 'error', 'vab-hey-message-error')
              }
            })
          } catch (e) {
            console.error(e)
          }
        } else {
          if (state.selectRows.length > 0) {
            try {
              const ids = state.selectRows.map((item) => item.id).join(',')
              $baseConfirm('你确定要删除选中项吗', '提示', async () => {
                const { msg } = await deleteBrand({ ids })
                $baseMessage(msg, 'success', 'vab-hey-message-success')
                await fetchData()
              })
            } catch (e) {
              console.error(e)
            }
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleDetail = (row) => {
        router.push(`/recycle/brandDetail?id=${row.id}`)
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNum = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNum = 1
        fetchData()
      }
      const fetchData = async () => {
        try {
          state.listLoading = true
          const { data } = await getList(state.queryForm)
          state.list = data.list
          state.total = data.total
          state.listLoading = false
        } catch (e) {
          console.error(e)
        }
      }
      /**
       * 获取部门分类列表
       * @returns {Promise<void>}
       */
      const fetchDeptListData = async () => {
        try {
          const { data: data } = await fetchDeptList()
          state.deptListData = data
        } catch (e) {
          console.error(e)
        }
      }
      onMounted(() => {
        fetchData()
        fetchDeptListData()
      })

      return {
        ...toRefs(state),
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        handleDetail,
        handleAddEdit,
        handleAssign,
        rowClass,
        handleSelectionChange,
        toggleSelection,
        dblclick,
        // fetchDictListState,
        Delete,
        Plus,
        Search,
        FolderDelete,
        Edit,
        Message,
        Document,
        FolderChecked,
        role,
        permission,
      }
    },
  })
</script>

<style scoped>
  .toolbar {
    margin-bottom: 4px;
  }

  .el-dropdown-link {
    display: flex;
    align-items: center;
    color: #1890ff;
    cursor: pointer;
  }

  :deep() .el-table .slecleRowColor {
    background: #eaf4ff !important;
  }

  :deep() .el-table tbody tr:hover > td {
    background-color: #eaf4ff !important;
  }

  :deep() {
    .cell .el-button {
      width: 32px;
    }
  }
</style>
